﻿using MyFile.Config;
using MyFile.Controllers;
using MyFile.Utils;
using Newtonsoft.Json;

namespace MyFile.Service
{
    public class UU
    {
        private static readonly Lazy<UU> lazy = new Lazy<UU>(() => new UU());
        public static UU Instance { get { return lazy.Value; } }  

        List<DBGoodsList> list = new List<DBGoodsList>();

        public List<GoodsTime> good = new List<GoodsTime>();

        int count = 0;

        public UU()
        {
            string configfilepath = Path.Combine(Program.path, "Config.json");

            string config = File.ReadAllText(configfilepath);
            if (!string.IsNullOrEmpty(config)) good = JsonConvert.DeserializeObject<List<GoodsTime>>(config);
            else good = new List<GoodsTime>();

            Program.dBUU = DBHelper.Instance.mDB.CopyNew().Queryable<DBUU>().First();

            //Thread t = new Thread(UUGET);
            //t.IsBackground = true;
            //t.Start();
        }
        public void UUGET()
        {
            try
            {
                Program.dBUU = DBHelper.Instance.mDB.CopyNew().Queryable<DBUU>().First();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Thread.Sleep(30000);
            }
        }
        public void UUGETThread()
        {
            while (true)
            {
                try
                {
                    Console.WriteLine($"进行第{count++}遍调用API");
                    list = DBHelper.Instance.mDB.CopyNew().Queryable<DBGoodsList>().ToList();
                    foreach (var item in list)
                    {
                        ReceiveGoodList listItem = null;
                        if (item.doppler == "No")
                            listItem = GetUU(item.templateId.ToString());
                        else
                            listItem = GetUU(item.templateId.ToString(), item.doppler);
                        if (listItem == null)
                        {
                            Thread.Sleep(60000);
                            continue;
                        }
                        if (item.price != double.Parse(listItem.Data[0].price))
                        {
                            item.price = double.Parse(listItem.Data[0].price);
                            item.inventory = listItem.TotalCount;
                            foreach (var gds in good)
                            {
                                if (gds.GoodsName == item.stickerName)
                                {
                                    if (gds.GoodsLists.Count > 100)
                                    {
                                        gds.GoodsLists.RemoveAt(0);
                                        gds.GoodsLists.Add(new GoodsList() { GoodsPrice = item.price, GoodsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
                                    }
                                    else
                                    {
                                        gds.GoodsLists.Add(new GoodsList() { GoodsPrice = item.price, GoodsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
                                    }
                                }
                            }
                            string json = JsonConvert.SerializeObject(good);
                            File.WriteAllText(Path.Combine(Program.path, "Config.json"), json);
                            int count = DBHelper.Instance.mDB.CopyNew().Updateable(item).ExecuteCommand();
                            if (count > 0)
                            {
                                Console.WriteLine($"{item.stickerName}价格变化，已更新到数据库，价格为{item.price}");
                                MethodService.Instance.SetEmail("2863614983@qq.com", $"{item.stickerName}的价格变化", $"价格为：{item.price}，量：{item.inventory}");
                            }
                        }
                        Thread.Sleep(60000);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"更新饰品价格时出现问题！\r\n{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 发送请求获取商品列表
        /// </summary>
        public ReceiveGoodList GetUU(string templateid)
        {
            try
            {
                var body = new
                {
                    gameId = "730",
                    listSortType = 1,
                    listType = "1",
                    pageIndex = 1,
                    pageSize = 1,
                    templateId = templateid
                };
                string a = CS2HttpUtils.DoPost(Program.dBUU.requestApiUrl, JsonConvert.SerializeObject(body));
                if (a == "0")
                {
                    Console.WriteLine($"请求失败，--{a}");
                    return null;
                }
                ReceiveGoodList d = JsonConvert.DeserializeObject<ReceiveGoodList>(a);
                return d;
            }
            catch(Exception ex)
            {
                Console.WriteLine($"报错{ex.Message}");
                return null;
            }
        }
        public ReceiveGoodList GetUU(string templateid,string keyWord)
        {
            try
            {
                var body = new
                {
                    gameId = "730",
                    keyWords = keyWord,
                    listSortType = 1,
                    listType = "10",
                    pageIndex = 1,
                    pageSize = 1,
                    templateId = templateid
                };
                string a = CS2HttpUtils.DoPost(Program.dBUU.requestApiUrl, JsonConvert.SerializeObject(body));
                if (a == "0")
                {
                    Console.WriteLine($"请求失败，--{a}");
                    return null;
                }
                ReceiveGoodList d = JsonConvert.DeserializeObject<ReceiveGoodList>(a);
                return d;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetUU方法报错，{ex.Message}");
                return null;
            }
        }
        /// <summary>
        /// 删除饰品
        /// </summary>
        /// <param name="templateid"></param>
        /// <returns></returns>
        public bool DeleteUU(UUDeleteGoodConfig deleteGoodConfig)
        {
            try
            {
                int count = DBHelper.Instance.mDB.CopyNew().Deleteable<DBGoodsList>().Where(a => a.templateId.ToString() == deleteGoodConfig.templateid && a.doppler == deleteGoodConfig.doppler).ExecuteCommand();
                if (count > 0)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        public string PostUU(string templateid)
        {
            try
            {
                ReceiveGoodList item = GetUU(templateid);
                if (item == null)
                {
                    return "NG，获取商品列表失败";
                }
                else
                {
                    DBGoodsList goodsList = new DBGoodsList();
                    goodsList.templateId = item.Data[0].templateId;
                    goodsList.stickerName = item.Data[0].commodityName;
                    goodsList.typeName = item.Data[0].typeName;
                    goodsList.doppler = "No";
                    goodsList.price = double.Parse(item.Data[0].price);
                    goodsList.inventory = item.TotalCount;
                    good.Add(new GoodsTime() { GoodsName = goodsList.stickerName, GoodsLists = new List<GoodsList>() { new GoodsList() { GoodsPrice = goodsList.price, GoodsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") } } });
                    string json = JsonConvert.SerializeObject(good);
                    File.WriteAllText(Path.Combine(Program.path, "Config.json"), json);
                    int count = DBHelper.Instance.mDB.CopyNew().Insertable(goodsList).ExecuteCommand();
                    if (count > 0)
                        return "OK";
                    else
                        return "NG，插入数据库失败";
                }  
            }
            catch (Exception ex)
            {
                return $"NG，出现异常：{ex.Message}";
            }
        }

        public string PostUU(string templateid,string keyWord)
        {
            try
            {
                ReceiveGoodList item = GetUU(templateid,keyWord);
                if (item == null)
                {
                    return "NG，获取商品列表失败";
                }
                else
                {
                    DBGoodsList goodsList = new DBGoodsList();
                    goodsList.templateId = item.Data[0].templateId;
                    goodsList.stickerName = item.Data[0].commodityName + "-" + item.Data[0].dopplerName;
                    goodsList.typeName = item.Data[0].typeName;
                    goodsList.doppler=item.Data[0].dopplerName;
                    goodsList.price = double.Parse(item.Data[0].price);
                    good.Add(new GoodsTime() { GoodsName = goodsList.stickerName, GoodsLists = new List<GoodsList>() { new GoodsList() { GoodsPrice = goodsList.price, GoodsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") } } });
                    string json = JsonConvert.SerializeObject(good);
                    File.WriteAllText(Path.Combine(Program.path, "Config.json"), json);
                    int count = DBHelper.Instance.mDB.CopyNew().Insertable(goodsList).ExecuteCommand();
                    if (count > 0)
                        return "OK";
                    else
                        return "NG，插入数据库失败";
                }
            }
            catch (Exception ex)
            {
                return $"NG，出现异常：{ex.Message}";
            }
        }
    }
}
